package com.zhou.kotlin_car_data_list.ui

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import com.zhou.kotlin_car_data_list.R
import com.zhou.kotlin_car_data_list.adapter.LogoAdapter
import com.zhou.kotlin_car_data_list.bean.Brand
import com.zhou.kotlin_car_data_list.bean.LogoBean
import com.zhou.kotlin_car_data_list.databinding.ActivityLogoBinding
import com.zhou.kotlin_car_data_list.utils.CarApi
import com.zhou.kotlin_car_data_list.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Response

class LogoActivity : AppCompatActivity() {

    val binding: ActivityLogoBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_logo)
    }

    val mData = mutableListOf<Brand>()

    val adapter: LogoAdapter by lazy {
        LogoAdapter(this, mData)
    }

    var letter_msg = "当前品牌首字母:"
    var letter = "A"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.logoAdapter = adapter
        binding.name = letter_msg + letter
        loadDatas(letter)
        binding.logoBtn.setOnClickListener(object : OnClickListener {
            override fun onClick(p0: View?) {
                var lt = binding.logoEd.text.trim().toString().uppercase()
                if (!TextUtils.equals(lt, letter)) {
                    letter = lt.toString()
                    binding.name = letter_msg + letter
                    loadDatas(letter)
                }
            }
        })
    }

    private fun loadDatas(letter: String) {
        val api = RetrofitUtils.getApi(CarApi.baseUrl, CarApi::class.java)
        val call = api.getCarLogo(CarApi.key, letter)
        call?.enqueue(object : retrofit2.Callback<LogoBean> {
            override fun onResponse(call: Call<LogoBean>, response: Response<LogoBean>) {
                val bean: LogoBean? = response.body()
                mData.clear()
                adapter.addDatas(bean?.result)
            }

            override fun onFailure(call: Call<LogoBean>, t: Throwable) {
                Log.d("zhourui_car", t.message.toString())
                Toast.makeText(this@LogoActivity, "加载失败", Toast.LENGTH_SHORT).show()
            }

        })
    }


}